#include "button.h"
#include "driver/gpio.h"
#include "driver/gptimer_types.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/queue.h"
#include "led.h"
#include "ntp.h"
#include "nvs.h"
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <stdio.h>
#include "pwm/led_pwm.h"

#define TAG "soft_timer"

extern void soft_start(void (*periodic_timer_callback)(void *arg),
                       int *period);
extern void hardware_start(void);

static int a = 1000000 * 5;

// 用于任务和ISR之间的队列
QueueHandle_t gpio_evt_queue = NULL;

void periodic_timer_callback(void *arg) {
  int64_t time_us = esp_timer_get_time();
  int *period = (int *)arg;
  ESP_LOGI(TAG, "定时器触发,period = %d us, tick = %lld\n", *period, time_us);

  // gpio_dump_io_configuration(stdout, (1ULL << 2) | (1ULL << 23));

  turn_on();
  vTaskDelay(1000 / portTICK_PERIOD_MS);
  turn_off();

  print_time();
}

void IRAM_ATTR button_click_callback(void *arg) {
  int val = 1;
  ESP_DRAM_LOGI(TAG, "Interrupt triggered!\n");
  xQueueSendFromISR(gpio_evt_queue, &val, NULL);
}

extern "C" void app_main(void) {
  esp_event_loop_create_default();

  gpio_evt_queue = xQueueCreate(10, sizeof(int));
  nvs_flash_init_custom();
  

  soft_start(&periodic_timer_callback, &a); // 1000ms
  led_init(GPIO_NUM_2);
  hardware_start();
  esp_timer_dump(stdout);
  
  listen_button_click(GPIO_NUM_22, &button_click_callback);

  xTaskCreatePinnedToCore(
      [](void *arg) {
        wifi_task(gpio_evt_queue);
        vTaskDelete(NULL);
      },
      "pwm_loop", 4096 * 2, NULL, 4, NULL, 0);

  xTaskCreatePinnedToCore(
      [](void *arg) {
        init_pwm();
        start_led_pwm();
        vTaskDelete(NULL);
      },
      "pwm_loop", 4096 * 2, NULL, 4, NULL, 1);
}
